<?php

namespace App\Http\Controllers;

use App\Models\Announcement;
use App\Models\Book;
use App\Models\BookCategory;
use App\Models\BookComment;
use App\Models\BorrowBook;
use App\Models\ChatRoom;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{

    public function index(Request $request)
    {
        // 渲染列表
        $sort = $request->input('sort', 'new');
        $dataList = Book::with('category');
        if ($sort == 'new') {
            $dataList = $dataList->orderBy('created_at', 'desc');
        } elseif ($sort == 'borrow') {
            $dataList = $dataList->orderBy('borrow_num', 'desc');
        } elseif ($sort == 'view') {
            $dataList = $dataList->orderBy('view_num', 'desc');
        } else {
            $dataList = $dataList->orderBy('created_at', 'desc');
        }


        $borrowSort = Book::orderBy('borrow_num', 'desc')->limit(12)->get();

        $ad = Announcement::orderBy('created_at', 'desc')->limit(3)->get();

        $records = BorrowBook::with(['user','book'])->whereIn('status', [BorrowBook::STATUS_BORROW, BorrowBook::STATUS_RETURN])->orderBy('created_at', 'asc')->limit(10)->get();

        $dataList = $dataList->limit(8)->get();
        return view('index', compact('dataList', 'sort', 'borrowSort','records','ad'));
    }


    public function categorySearch(Request $request)
    {
        $category = BookCategory::orderBy('sort', 'asc')->get();

        $current = $request->input('current', '');
        $title = $request->input('title', '');
        $dataList = Book::with('category');


        if ($current != '') {
            $dataList = $dataList->where('category_id', $current);
        }

        if ($title != '') {
            $dataList = $dataList->where('title', 'like', '%' . $title . '%');
        }

        $dataList = $dataList->limit(8)->paginate(12);
        return view('categorySearch', compact('dataList', 'category', 'title', 'current'));
    }


    public function book(Request $request, Book $book)
    {
        $bookComment = BookComment::with('user')->where('book_id', $book->id)->orderBy('created_at', 'asc')->get();

        $book->view_num = $book->view_num + 1;
        $book->save();
        return view('book', compact('book', 'bookComment'));
    }

    public function chat(Request $request)
    {
        return view('chat');
    }


    public function postBookComment(Request $request)
    {
        $content = $request->input('content');

        BookComment::create([
            'user_id' => auth()->id(),
            'content' => $content,
            'book_id' => $request->input('book_id')
        ]);
        return redirect('/book/' . $request->input('book_id'))->with('success', '评论成功');
    }

    public function postChat(Request $request)
    {
        $content = $request->input('content');

        ChatRoom::create([
            'user_id' => auth()->id(),
            'content' => $content,
        ]);
        return redirect('/chat/')->with('success', '评论成功');
    }

    /**
     * 用户借阅
     * @param Request $request
     * @param Book $book
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function borrow(Request $request, Book $book)
    {
        if ($book->status == Book::STATUS_DOWN) {
            return redirect('/book/' . $book->id)->withErrors(['该图书已被下架']);
        }
        if ($book->stock <= 0) {
            return redirect('/book/' . $book->id)->withErrors(['该图书已被借完']);
        }

        // 查找已经借的,和未审批的总数
        $already = BorrowBook::where('user_id', auth()->id())->whereIn('status', [BorrowBook::STATUS_BORROW, BorrowBook::STATUS_APPROVAL])->count();

        // 获取可以借出去多少本
        $can = auth()->user()->level->borrow_num;
        if ($can <= $already) {
            return redirect('/book/' . $book->id)->withErrors(['您已经借阅了' . $already . '本,不能再借了']);
        }


        DB::beginTransaction();
        try {
            // 开始借书
            BorrowBook::create([
                'user_id' => auth()->id(),
                'book_id' => $book->id,
                'borrow_date' => Carbon::now(),
                'illegal' => '',
                'status' => BorrowBook::STATUS_APPROVAL,
            ]);
            DB::commit();
            return redirect('/book/' . $book->id)->with('success', '借阅成功，请等待借阅审核员审核');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect('/book/' . $book->id)->withErrors(['借阅失败']);
        }
    }


    public function audit(Request $request)
    {
        $id = $request->input('id');
        $type = $request->input('type');
        $model = BorrowBook::find($id);
        DB::beginTransaction();
        try {
            $model->status = $type;
            $model->manage_id = auth()->user()->id;
            $model->save();
            if ($type ==1){
                $book = Book::find($model->book_id);
                if ($book->stock <= 0) {
                    return redirect('/userCenter?type=audit')->withErrors(['该图书已被借完']);
                }
                $book->borrow_num = $book->borrow_num + 1;
                $book->stock = $book->stock - 1;
                $book->save();

                // 开始升级
                // 查看用户借阅总数
                $borrowNum = BorrowBook::where('user_id', $model->user_id)->whereIn('status', [BorrowBook::STATUS_BORROW, BorrowBook::STATUS_RETURN])->count();
                $user = \App\Models\User::find($model->user_id);
                if ($borrowNum >= $user->level->score) {
                    $user->level_id = $user->level_id + 1;
                    $user->save();
                }
            }
            DB::commit();;
            return redirect('/userCenter?type=audit')->with('success', '操作成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect('/userCenter?type=audit')->withErrors(['操作失败']);
        }
    }


    public function returnBook(Request $request)
    {
        $id = $request->input('id');

      DB::beginTransaction();
        try {
            $model = BorrowBook::find($id);
            $model->status = BorrowBook::STATUS_RETURN;
            $model->return_date = Carbon::now();
            $model->save();

            // 更新书的库存

            $book = Book::find($model->book_id);
            $book->stock = $book->stock + 1;
            $book->save();

            DB::commit();

            return redirect('/userCenter?type=records')->with('success', '归还成功');

        }catch (\Exception $e){
            DB::rollBack();

            return redirect('/userCenter?type=records')->with('success', '归还失败');

        }
    }


    public function ad(Request $request,Announcement $announcement)
    {

        return view('ad',compact('announcement'));
    }

}
